<template>
  <div id="app">
    <!-- 头部 -->
    <hd_comp>
      <template slot="login">
        <el-button @click="dialogVisible = true" v-if="!islogin">登录</el-button>
        <img v-else @click="myInfoVisible = true" class="login" :src="loginsrc || require('@/assets/static/img/my.png')">
      </template>
    </hd_comp>
    <!-- 路由 -->
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive">
      </router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive">
    </router-view>
    <!-- 尾部 -->
    <ft_comp></ft_comp>

    <!-- 登录弹窗 -->
    <el-dialog @close="closeDialog" title="欢迎来到海螺博客" :close-on-click-modal=false append-to-body
      :visible.sync="dialogVisible" width="400px">
      <el-form ref="form" :rules="rules" :model="form" label-width="60px">
        <el-form-item label="邮箱" prop="username">
          <el-input v-model="form.username" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="dialogType" label="手机" prop="cellphone">
          <el-input v-model="form.cellphone" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="dialogType" label="昵称" prop="nickname">
          <el-input v-model="form.nickname" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input :type="inputType ? 'text' : 'password'" v-model="form.password" clearable>
            <i @click="inputType = !inputType" slot="suffix" :class="[inputType ? 'icon-yanjing-' : 'icon-yanjing_bi']"
              class="iconfont "></i>
          </el-input>
        </el-form-item>
        <el-row :gutter="10" style="padding: 0 30px;">
          <el-col :span="12">
            <el-checkbox v-model="checked">记住密码</el-checkbox>
          </el-col>
          <el-col :span="12">
            <el-link style="float: right;" type="primary" @click="dialogType = !dialogType">注册/登录</el-link>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-row :gutter="50" style="padding: 0 30px;">
          <el-col :span="12">
            <el-button style="width: 100%;" type="info" @click="$refs.form.resetFields()">重置</el-button>
          </el-col>
          <el-col :span="12">
            <el-button style="width: 100%;" type="primary" @click="submit">确 定</el-button>
          </el-col>
        </el-row>
      </span>
    </el-dialog>

    <!-- 个人信息弹窗 -->
    <el-dialog title="个人资料" :close-on-click-modal="false" append-to-body :visible.sync="myInfoVisible" width="400px">
      <el-row style="line-height: 30px;">
        <el-col style="text-align: center;">
          <img class="login" :src="loginsrc || require('@/assets/static/img/my.png')">
        </el-col>
        <el-col style="text-align: center;">
          <p>{{ `${myinfo.nickname}(${myinfo.sex})` }}</p>
        </el-col>
        <el-col style="text-align: center;">
          <p>{{ `${myinfo.birthday}` }}</p>
        </el-col>
        <el-col style="text-align: center;">
          <p>{{ `${myinfo.username}` }}</p>
        </el-col>
        <el-col style="text-align: center;">
          <p>{{ `${myinfo.autograph || '无'}` }}</p>
        </el-col>
        <el-col style="text-align: center;margin-top: 20px;">
          <el-button type="primary" @click="setUserInfoVisible = true">修改资料</el-button>
          <el-button @click="exit">退出登录</el-button>
        </el-col>
      </el-row>

      <el-dialog width="450px" title="修改个人资料" :close-on-click-modal="false" :visible.sync="setUserInfoVisible"
        append-to-body>
        <el-form :model="setUserForm" ref="setUserForm" label-width="100px" class="demo-ruleForm">
          <!-- 头像 -->
          <el-upload class="avatar-uploader" action="#" :http-request="httpRequest" :show-file-list="false">
            <img v-if="loginsrc" :src="loginsrc" class="avatar">
            <i v-if="loginsrc" @click.stop="loginsrc = ''" class="x el-icon-circle-close"></i>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!-- 姓名 -->
          <el-form-item label="昵称">
            <el-input disabled v-model="setUserForm.nickname"></el-input>
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item label="邮箱">
            <el-input disabled v-model="setUserForm.username"></el-input>
          </el-form-item>
          <!-- 性别 -->
          <el-form-item label="性别">
            <el-select style="width: 100%;" v-model="setUserForm.sex" placeholder="请选择">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <!-- 生日 -->
          <el-form-item label="生日">
            <el-date-picker value-format="yyyy-MM-dd" type="date" placeholder="选择日期" v-model="setUserForm.birthday"
              style="width: 100%;"></el-date-picker>
          </el-form-item>
          <!-- 个签 -->
          <el-form-item label="个签">
            <el-input type="textarea" v-model="setUserForm.autograph"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="setUserInfo" type="primary">确定修改</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import hd_comp from "./components/header.vue";
import ft_comp from "./components/footer.vue";
import { login, userinfo, reguser, setUserInfo, getPageInfo } from "@/api/index";
import { setToken, removeToken } from "@/utils/token";
export default {
  name: 'App',
  components: {
    hd_comp,
    ft_comp,
  },
  data() {
    return {
      loginsrc: '',
      islogin: false, // 是登录状态
      dialogVisible: false, // dialog
      inputType: true, // 密码框模式
      checked: true, // 是否记住密码
      dialogType: false, // 是注册模式
      myInfoVisible: false, //个人资料弹框
      setUserInfoVisible: false, // 修改当前用户信息弹窗
      myinfo: {},
      form: {
        type: 0,
        username: "",
        password: "",
        cellphone: '',
        nickname: '',
      },
      rules: {
        username: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        cellphone: [
          { required: true, message: '请输入手机', trigger: 'blur' },
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
        ]
      },
      setUserForm: {},
      form1: {
        affiche: '',
        intro: '',
        qq: '',
        wx: '',
        rests: '',
      },
      form2: {
        short: {
        },
      },
      form3: {
        education: [
          {
            title: '',
            body: ''
          }
        ],
        work: [
          {
            title: '',
            body: ''
          }
        ],
      },
      form4: {
        technology: [
          {
            title: '',
            body: '',
            imageUrl: '',
          }
        ],
      }
    }
  },
  mounted() {
    if (this.$cache.local.getJSON('userinfo')) {
      this.form.username = this.$cache.local.getJSON('userinfo').username
      this.form.password = this.$cache.local.getJSON('userinfo').password
      if (this.$cache.local.getJSON('userinfo').state) {
        this.islogin = true
        // 获取当前头像信息
        userinfo().then(res => {
          res.data.data.birthday = res.data.data.birthday ? this.$moment(res.data.data.birthday, 'YYYY-MM-DD') : ''
          this.myinfo = res.data.data
          this.setUserForm = res.data.data
          this.loginsrc = res.data.data.user_pic
          // 添加登录状态
          res.data.data.state = true
          this.$store.commit('SET_USER', res.data.data)
        })
      }
    }
    getPageInfo().then(res => {
      //映射数据
      for (let key in this.form1) {
        this.form1[key] = res.data.results[0][key]
      }
      for (let key in this.form2) {
        this.form2[key] = this.jsontojs(res.data.results[0][key])
      }
      for (let key in this.form3) {
        this.form3[key] = this.jsontojs(res.data.results[0][key])
      }
      for (let key in this.form4) {
        this.form4[key] = this.jsontojs(res.data.results[0][key])
      }
      let pageData = { ...this.form1, ...this.form2, ...this.form3, ...this.form4 }
      this.$store.commit('SET_PAGE', pageData)
    })
  },
  methods: {
    closeDialog() {
      this.$refs.form.resetFields()
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 校验成功
          if (!this.dialogType) {
            // 登录模式
            login(this.form).then(res => {
              if (!res.data.status) {
                this.$message.error(res.data.message)
                return
              } else {
                setToken(res.data.token)
                //保存登录信息
                let userinfo = {
                  username: this.form.username,
                  password: this.form.password,
                  state: true,
                }
                if (this.checked) {
                  this.$cache.local.setJSON('userinfo', userinfo)
                }
                this.dialogVisible = false
                this.$message.success('登录成功')
                this.$router.go(0)
              }
            })
          } else {
            // 注册模式
            reguser(this.form).then(res => {
              if (!res.data.status) {
                this.$message.error(res.data.message)
              } else {
                this.dialogType = false
                this.$message.success('注册成功')
              }
            })
          }
        } else {
          //校验失败
          return false;
        }
      });


    },
    exit() {
      removeToken();
      let userinfo = this.$cache.local.getJSON('userinfo')
      userinfo.state = false
      this.$cache.local.setJSON('userinfo', userinfo)
      this.myInfoVisible = false
      this.$router.go(0)
    },
    // 上传图片
    httpRequest(e) {
      let res = !e.file ? e.target.files[0] : e.file; //兼容原生和element 上传
      let reader = new FileReader()
      reader.readAsDataURL(res)
      reader.onload = () => {//加载完立即触发
        this.loginsrc = reader.result
      }
    },
    // 修改信息提交
    setUserInfo() {
      let query = {
        ...this.setUserForm
      }
      delete query.state
      if (this.loginsrc) {
        query.user_pic = this.loginsrc
      }
      // 修改
      setUserInfo(query).then(res => {
        if (!res.data.status) {
          this.$message.error('修改失败')
        } else {
          this.$message.success('修改成功')
          this.setUserInfoVisible = false
          this.myInfoVisible = false
        }
      })
    },
    //js 转 json 转化函数
    jsontojs(obj) {
      //深拷贝
      function deepCopy(value) {
        if (value instanceof Function) return value
        else if (value instanceof Array) {
          var newValue = []
          for (let i = 0; i < value.length; ++i) newValue[i] = deepCopy(value[i])
          return newValue
        } else if (value instanceof Object) {
          var newValue = {}
          for (let i in value) newValue[i] = deepCopy(value[i])
          return newValue
        } else return value
      }
      let newobj = deepCopy(obj)
      //定义数组和长度
      newobj = JSON.parse(newobj)
      //循环判断类型push
      return newobj
    },
  }
}
</script>

<style lang="less">
#app {
  height: 100%;
}
</style>
<style lang="less" scoped>
.login {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.el-dialog__wrapper {
  /deep/ .avatar-uploader {
    position: relative;
    text-align: center;
    margin-bottom: 20px;

    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;

      &:hover {
        border-color: #409EFF;
      }
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .avatar {
      vertical-align: bottom;
      width: 130px;
      height: auto;
    }

    .x {
      position: absolute;
      top: 0;
      right: 0;
      background-color: #eee;
      border-radius: 50%;
    }

    .el-icon-plus {
      width: 130px;
      height: 130px;
      line-height: 130px;
    }
  }
}
</style>